package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.MessageContact;
import com.isunland.managesystem.utils.LogUtil;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AppointerListFragment extends BaseListFragment {
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  public static final String EXTRA_FROM = "com.isunland.managesystem.ui.EXTRA_FROM";
  public static final int VALUE_TO_DO = 1;
  private AppointerAdapter mAdapter;
  private ArrayList<MessageContact> mList;
  private EditText mSearchEt;
  private int mFrom;//来自于,用于区分不同页面或控件.

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.selectPerson);

    mFrom = getArguments().getInt(EXTRA_FROM);

    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mListview.setDivider(null);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, null, false);
    mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    mSearchEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mList == null || mList.size() == 0) {
          return;
        }
        String query = s.toString().trim();
        if (query == null || query.equals("")) {
          setAdapter(mList);
        } else {
          updateItems(query);
        }

        mSearchEt.requestFocus();
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Auto-generated method stub

      }

      @Override public void afterTextChanged(Editable s) {
        // Auto-generated method stub

      }
    });
    TextView mDepartmentTv = (TextView) header.findViewById(R.id.tv_department_searchPersonHeader);
    mDepartmentTv.setText(CurrentUser.newInstance(getActivity()).getDeptName());
    mListview.addHeaderView(header);
  }

  @Override public String getUrl() {
    // Auto-generated method stub
    return ApiConst.URL_QUERY_MEMBER;
  }

  @Override public HashMap<String, String> getparameters() {

    HashMap<String, String> params = new HashMap<>();
    params.put("type", "user");
    String memberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
    params.put("orgCode", memberCode);
    return params;
  }

  @Override public void resolveResponse(String json) {
    Type listType = new TypeToken<ArrayList<MessageContact>>() {
    }.getType();

    mList = new Gson().fromJson(json, listType);

    setAdapter(mList);
  }

  private void setAdapter(List<MessageContact> detail) {

    if (mList == null) {
      mList = new ArrayList<>();
    }
    mAdapter = new AppointerAdapter(getActivity(), detail);
    setListAdapter(mAdapter);
    ((AppointerAdapter) getListAdapter()).notifyDataSetChanged();
  }

  public void updateItems(String query) {

    // 直接通过中文人名来进行搜索
    ArrayList<MessageContact> listNames = new ArrayList<>();// 获取人名
    String str;
    String deptStr;
    for (int i = 0; i < mList.size(); i++) {
      str = mList.get(i).getName();
      deptStr = mList.get(i).getDeptName();
      if (str.contains(query) || deptStr.contains(query)) {
        listNames.add(mList.get(i));
      }
    }

    setAdapter(listNames);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {

    MessageContact item = mAdapter.getItem(position - 2);

    CustomerDialog dialog;
    if (mFrom == VALUE_TO_DO) {
      // 待办中的转办需要的参数不同.
      dialog = new CustomerDialog(item.getName(), item.getId().toString());
    } else {
      dialog = new CustomerDialog(item.getName(), item.getJobNo());
    }
    Intent i = new Intent();
    i.putExtra(EXTRA_VALUE, dialog);
    LogUtil.i("name===" + dialog.getName() + ",id==" + dialog.getId());
    getActivity().setResult(Activity.RESULT_OK, i);
    getActivity().finish();
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        getActivity().finish();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public static AppointerListFragment newInstance(int from) {
    Bundle args = new Bundle();
    args.putInt(EXTRA_FROM, from);
    AppointerListFragment fragment = new AppointerListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
